<template>
    <div>
        <nav-bar>
            <template v-slot:default>
                购物车(<span>{{ $store.state.carCount }}</span>)
            </template>
           
        </nav-bar>
        <div class="car-box">
            <div class="car-body">
                
                <van-checkbox-group @change = "groupChange" v-model="result">
                    <van-swipe-cell :right-width="50"
                        v-for="(item,index) in list" :key="index"
                    >
                        <div class="good-item">
                            <van-checkbox :name="item.id"/>
                            <div class="good-img">
                                <img :src="item.goods.cover_url" alt="">
                            </div>
                            <div class="good-desc">
                                <div class="good-title">
                                    <span>{{ item.goods.title }}</span>
                                    <span>{{ item.goods.stock }}</span>
                                </div>
                                <div class="good-btn">
                                    <div class="price"><small>￥</small>{{ item.goods.price+'.00' }}</div>
                                    <!-- <van-stepper integer  :min="1" :max="item.goods.stock" 
                                    :model-value="item.num" :name="item.id" async-change @change="onChange"/> -->
                                    <van-stepper integer  :min="1" :max="item.goods.stock" 
                                    :model-value="item.num" :name="item.id" async-change @change="onChange"/>
                                </div>

                            </div>
                        </div>
                     
                        <template #right>
                                <van-button
                                    square
                                    icon="delete"
                                    type="danger"
                                   class="delete-button"
                                   @click="deleteGood(item.id)"
                                /></template>
                    </van-swipe-cell>
                </van-checkbox-group>
            </div>
            <van-submit-bar class="submit-all" :price="total*100" @submit="onSubmit" button-text="结算">
                <van-checkbox @click="allCheck" v-model:checked="checkAll">全选</van-checkbox>
            </van-submit-bar>
            <div class="empty" v-if="!list.length">
                <img class="empty-cart" src="~assets/images/empty-car.png" alt="空购物车"/>
                <div class="title">购物车空空如也</div>
                <van-button round color="#lbaeae" type="primary" block @click="goTo">前往选购</van-button>
            </div>
        </div>
    </div>
</template>


<style>
.car-body{
    margin:60px 0 100px 0;
    padding-left:10px;
}
.good-item{
    display:flex;
}
.good-item img{
    width:100px;
    height:auto;
}
.good-desc{
    display:flex;
    flex-direction:column;
    /* direction:方向 column：柱 */
    justify-content:space-between;
    /* justify:每行排齐 space:空间 */
    flex:1;
    padding:20px;

}
.good-title{
    display:flex;
    justify-content:space-between;

}
.good-btn{
    display:flex;
    justify-content:space-between;
}
.empty{
    width:50%;
    margin:0 auto;
    text-align:center;
    margin-top:200px;
}
.empty-cart{
    width:150px;
    margin-bottom:20px;
}
.delete-button{
    width:50px;
    height:100%;
}
.submit-all{
    margin-bottom:100px;
}
.van-checkbox{
    margin-left:0px;
}
.price{
    font-size: 16px;
    color: red;
    line-height: 28px;
}
</style>
<script>


import NavBar from '@/components/common/NavBar/NavBar.vue';
import{computed,onMounted,reactive,ref,toRefs} from 'vue'
//mounted:安装 reactive:反应的 ref:编号 
import { useRouter } from 'vue-router';
import { useStore } from 'vuex';
import { getCar,deleteCarItem,checkedCar,modifyCar } from '@/network/shopcar';
import { Toast } from 'vant';
// modify:修改
export default{
    name:"Shopcar",
    components:{
        NavBar
    },
    setup(){
        // let allCheck = ref(null)
        
        const router = useRouter()
        // router:路由器
        // 数据模型，状态
        const store = useStore()
        const state = reactive({
            list:[],
            result:[],//数组
            checkAll:true
        })
        // 初始化购物车数据
        const init=()=>{
            // init:初始化
            Toast.loading({
                message:'加载中....',
                forbidClick:true
                //   forbid:禁止
            })
            // Toast:干杯;吐司;敬酒;祝酒;烤面包片
            getCar('include=goods').then(res=>{
                // include:包含
                console.log(res.data);
                state.list=res.data
                state.result = res.data.filter((n)=>n.is_checked==1).map(item=>item.id)
                Toast.clear()
                // clear:明确的

            })
        }
        onMounted(()=>{
            init()
        })
        // 通过计算属性计算总价
       const total=computed(()=>{
        let sum = 0
            state.list.filter(item=>state.result.includes(item.id))//includes()方法用来判断一个数组是否包含一个指定的值，如果是返回true,否则false
            .forEach(item=>{
                sum+=parseInt(item.num)*parseFloat(item.goods.price)
            })
            return sum
       })
        // 异步改变购物车数量
        const onChange=(value,detail)=>{
            // detail:详情
            console.log(value);
            console.log(detail);
            Toast.loading({
                message:'加载中....',
                forbidClick:true
                //   forbid:禁止
            })
            modifyCar(detail.name,{num:value}).then(res=>{
                // 将onMounted中的list中的num也要改
                state.list.forEach(item=>{
                    if(item.id == detail.name){
                        item.num = value
                    }
                })
                Toast.clear();
            })
        }
        // 前往购物
        const goTo=()=>{
            router.push('/home')
        }
        // 复选框改变处理
        // var one =document.getElementsByName('van-checkbox')
        const groupChange=(result)=>{
            if(result.length==state.list.length){
              
                state.checkAll=true
            }else{
              
                state.checkAll=false
            }
            console.log(state.checkAll);
            console.log(result);
            // 改变数据表中的选中状态
            checkedCar({cart_ids:result})
        }
        const allCheck=()=>{
            if(!state.checkAll){
                state.result = state.list.map(item=>item.id)
                state.checkAll=true
            }else{
                state.result=[]
                state.checkAll=false
            }
        }
        const deleteGood=(id)=>{
            deleteCarItem(id).then(res=>{
                init()
                // 重新初始化
                console.log('deleteCar');
                store.dispatch('updateCar')//改变vuex中的状态数据
            })
        }
        // 创建订单
        const onSubmit=()=>{
            if(state.result.length==0){
                Toast.fail('请选中商品进行结算')
                return
            }else{
                router.push('/createorder')
            }
        }
        return{
            ...toRefs(state),
            goTo,
            onChange,
            groupChange,
            allCheck,
            deleteGood,
            total,
            onSubmit
          
        }
    }
}
</script>
<!--  
reactive:反应 res:物品 filter:过滤器 state:状态 dispatch：发出 init:初始化 computed:计算 includes:包含 parse:解析 fail:失败

 -->